package com.hjy.attendance.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hjy.attendance.context.IMContextHolder;
import com.hjy.attendance.dao.AttendanceParentDao;
import com.hjy.attendance.entity.*;
import com.hjy.attendance.enums.ResultEnum;
import com.hjy.attendance.exception.ApiException;
import com.hjy.attendance.service.*;
import com.hjy.attendance.util.BeanUtil;
import com.hjy.attendance.util.JwtUtil;
import com.hjy.attendance.util.RedisUtil;
import com.hjy.attendance.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;


/**
 * <p>标题:  Service 实现类</p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2020</p>
 *
 * @version: 1.0
 * @author: huangjunyu
 * @date 2020-04-18
 */
@Service
public class AttendanceParentServiceImpl extends BaseServiceImpl<AttendanceParentDao, AttendanceParent> implements AttendanceParentService {

    @Autowired
    CoursePickUpInfoService coursePickUpInfoService;

    @Autowired
    AttendanceSonService attendanceSonService;
    @Autowired
    RedisUtil redisUtil;

    @Autowired
    TeacherService teacherService;

    @Autowired
    CourseService courseService;

    @Autowired
    UserService userService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void publish(AttendanceParent attendanceParent) throws ApiException {
        if (StringUtils.isEmpty(attendanceParent.getCourseNo())){
            throw new ApiException(ResultEnum.CUSTOMFAILURE,"课程号不得为空");
        }
        QueryWrapper<AttendanceParent> parentQueryWrapper=new QueryWrapper<>();
        parentQueryWrapper.eq("publish_no",attendanceParent.getPublishNo()).eq("total_success_flag",0);
        if (list(parentQueryWrapper).size()>0){
            throw new ApiException(ResultEnum.CUSTOMFAILURE,"你当前还有一个考勤任务未结束");
        }
        QueryWrapper<CoursePickUpInfo> queryWrapper= new QueryWrapper<CoursePickUpInfo>();
        queryWrapper.eq("course_no",attendanceParent.getCourseNo());
        List<CoursePickUpInfo> coursePickUpInfos=this.coursePickUpInfoService.list(queryWrapper);
        if (coursePickUpInfos.isEmpty()){
            throw new ApiException(ResultEnum.CUSTOMFAILURE,"该课程下目前没有学生选修,考勤发布无意义");
        }
        attendanceParent.setGuid(UUID.randomUUID().toString());
        attendanceParent.setCreateTime(new Date());
        attendanceParent.setTotalSuccessFlag(0);
        Optional.ofNullable(insert(attendanceParent)).ifPresent(parent->{
            int seconds= (int) ((parent.getAllowTimeDifference().getTime()-System.currentTimeMillis())/1000);
            redisUtil.set(parent.getGuid(),parent.toString(),seconds);
            List<AttendanceSon> attendanceParentServices=new ArrayList<>(coursePickUpInfos.size());
            //批量插入
            coursePickUpInfos.stream().forEach(data->{
                AttendanceSon attendanceSon=AttendanceSon.builder()
                        .attentanceFlag(0)
                        .attentanceRecordStartTime(null)
                        .guid(UUID.randomUUID().toString())
                        .attentanceParentId(parent.getGuid())
                        .userId(data.getStudentNo())
                        .successFlag(0)
                        .ipv4Address(null)
                        .build();
                attendanceParentServices.add(attendanceSon);

            });
            attendanceSonService.insertBatch(attendanceParentServices);
        });

    }

    @Override
    public List<Map<String,Object>> getUnCompletedAttendances() throws Exception {
        String userId= JwtUtil.decode(IMContextHolder.get("token"));
        List<String> sons=this.attendanceSonService.list(new QueryWrapper<>(AttendanceSon.builder().userId(userId).successFlag(0).build())).stream().map(AttendanceSon::getAttentanceParentId).collect(Collectors.toList());
        QueryWrapper<AttendanceParent> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("total_success_flag",0);
        List<Map<String,Object>> result=list(queryWrapper).stream().filter(data->{
            return sons.contains(data.getGuid());
        }).map(BeanUtil::transBean2Map)
                .peek(data->{
                    data.put("courseName",courseService.getById(data.get("courseNo").toString()).getCourseName());
                    data.put("publishName",teacherService.getById(data.get("publishNo").toString()).getName());
                    data.put("content",new String((byte[])data.get("content")));
                }).collect(Collectors.toList());
        return result;

    }

    @Override
    public List<Map<String, Object>> getAttendanceInfo() throws Exception {
        return this.baseDao.getAttendanceInfo();
    }

    @Override
    public List<Student> getTeacherCourseStudents(String teacherId) throws Exception {
        List<Student> result=this.baseDao.getTeacherCourseStudents(teacherId);
        return result;
    }
}
